from time import strftime, localtime
import psutil
import xlwt

print("系统内存和CPU占用率记录")
num = int(input("请输入需记录多少组数据："))
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("Sheet Name1")
sheet.write(0, 0, '时间')  # row, column, value
sheet.write(0, 1, '系统内存占用率')
sheet.write(0, 2, '系统CPU占用率')
count = 1
for each in range(0, num):
    # 系统时间
    time_now = strftime("%Y-%m-%d %H:%M:%S", localtime())
    sheet.write(count, 0, time_now)  # row, column, value
    # 系统的内存利用率
    mem = psutil.virtual_memory().percent
    sheet.write(count, 1, mem)
    # 系统的CPU利用率
    # psutil.cpu_percent(None)
    # sleep(1)
    cpu = psutil.cpu_percent(interval=1)
    sheet.write(count, 2, cpu)
    print("当前是第{}组使用率:mem={}%,cpu={}%".format(count, mem, cpu))
    count = count + 1
    workbook.save('d:\\MemCpu.xls')
input("输入任意键结束")